package com.lxc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxc.entity.Result;
import com.lxc.entity.User;
import com.lxc.service.UserService;
import com.lxc.util.RSA;
import com.lxc.util.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService UserService;


    //    获取公钥
    @GetMapping("/getPublicKey")
    public Result<String> getPublicKey() {
        return Result.success(RSA.getPublicKeyStr());
    }

    //    注册
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        UserService.register(user);
        return Result.success("注册成功");
    }

    /*双令牌登录*/
    @PostMapping("/user-tokens")
    public Result<Map<String, Object>> login(@RequestBody User user) throws Exception {
        Map<String, Object> token = UserService.login(user);
        return Result.success(token);
    }

    /*当短时间的token过期，前端需要通过长时间的token来访问后端，并且生成一个短时间的token返回给前端，也就是刷新短时间的token。*/
    @PostMapping("/access-tokens")
    public Result<String> refreshAccessToken(HttpServletRequest request) throws Exception {
        String refreshToken = request.getHeader("refreshToken");
        String accessToken = UserService.refreshAccessToken(refreshToken);
        return Result.success(accessToken);
    }

    /*退出*/
    @DeleteMapping("/refresh-tokens")
    public Result<String> logout(HttpServletRequest request) {
        String refreshToken = request.getHeader("refreshToken");
        UserService.logout(refreshToken);
        return Result.success("退出成功");
    }

    /*除了刷新短期令牌需要用到refreshToken之外，其他的业务访问都先需要通过下面的
    UserSupport的getCurrentUserId()方法来通过短期令牌来获取userId，再进行业务操作。
    * */
    @GetMapping
    public Long getCurrentUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = requestAttributes.getRequest().getHeader("accessToken");
        Long userId = Token.verifyToken(token);
        if (userId < 0) {
            throw new RuntimeException("非法用户");
        }
        return userId;
    }


}